<template>
	<page-meta :page-style="'overflow:'+(pageMetaShow?'hidden':'visible')"></page-meta>
	<view class="content">
		<view class="item">
			<button @click="linkUrl('/pages/package/index',1)">背包</button>
			<button @click="linkUrl(`/pages/index/gashaponGuide?shopId=${shopId}&machineId=${machineId}`)">图鉴{}</button>
			<button @click="linkUrl('/pages/my/help')">联系</button>
		</view>
		<view class="item">

			<button @click="gashaponFn(machine.combo_draw_times)"
				v-if="machine.combo_draw_switch==1">扭{{machine.combo_draw_times}}次</button>
			<button @click="gashaponFn(1)">一发入魂￥{{machine.price}}</button>
			<button @click="boxPlay" v-if="machine.box_selling==1">差价端盒￥{{machine.box_price}}</button>
			<!-- @click="ordersCreateFn(undefined,'lotterybox')" -->
		</view>
		<view class="item">
			<!-- direct_purchase_enabled 是否自选直购 -->
			<button 
			@click="ToggleB"
				v-if="machine.direct_purchase_enabled==1">直购</button><!-- 自选直购 -->
			 <!-- @click="linkUrl(`/pages/index/Self-selectedDirectPurchase?shopId=${shopId}&machineId=${machineId}`)" -->
			<!-- trial_enabled = 0|1 是否显示试一试按钮 -->
			<button v-if="machine.trial_enabled==1" @click="haveShotFn">试一试</button>
		</view>
		<view class="item">
			<button @click="Toggle2">转发</button>
		</view>
		<uni-popup ref="popupFL" @change="changePopup" safeArea>
			<!-- isMaskClick='true'> -->
			<claimBenefitsPop ref="claimBenefitsPop" :machineId="machineId"></claimBenefitsPop>
		</uni-popup>
		<uni-popup ref="popupB" @change="changePopup" safeArea>
			<view style="height: 70vh;">
				<!-- 因为总变，最后不知道是页面还是弹窗。所以直接引用页面 -->
				<selfSelectedDirectPurchase ref="selfSelectedDirectPurchase" @results="closePopB"></selfSelectedDirectPurchase>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import selfSelectedDirectPurchase from '@/pages/index/Self-selectedDirectPurchase.vue'
	export default {
		components: {
		    selfSelectedDirectPurchase
		  },
		data() {
			return {
				shopId: '',
				machineId: '',
				machine: {},
				haveShotList: [], //试一试列表
				totalWeight: 0, //总权重
				selectedItem: null,
				selectedIndex: -1,
				pageMetaShow: false,
			};
		},
		onLoad(e) {
			// 移除用户选择的缓存数据
			uni.removeStorageSync('userSelects');
			uni.removeStorageSync('userSelectsIds');
			this.shopId = e.shopId;
			this.machineId = e.machineId;
			this.machinesDetailFn();
			// this.Toggle2() 
		},
		methods: {
			linkUrl(url, type = 0) {
				if (type == 0) {

					uni.navigateTo({
						url
					})
				} else {

					uni.reLaunch({
						url
					})
				}
			},
			// 转发弹窗
			Toggle2() {
				this.$refs.popupFL.open('left');
				// this.$refs.claimBenefitsPop.forwardSettingFn()
			},
			
			closePop2() {
				this.$refs.popupFL.close()
			},
			closePopB() {
				this.$refs.popupB.close()
			},
			ToggleB(){
				let that=this;
				this.$refs.popupB.open('bottom');
				
				this.$refs.selfSelectedDirectPurchase.refsLoad(this.shopId,this.machineId);
			},
			changePopup(e) {
				this.pageMetaShow = e.show
			},
			// 端盒购买
			boxPlay() {
				uni.setStorageSync('userSelects', this.machine)
				this.linkUrl(
					`/pages/my/orderConfirmation?price=${this.machine.box_price}&playType=lotterybox&shopId=${this.shopId}&machineId=${this.machineId}`
				)
			},
			// 试一试
			haveShotFn() {
				// 生成一个随机数，范围在0到总权重之间
				const random = Math.random() * this.totalWeight;
				// 遍历数组，累加权重，直到找到随机数落在的区间
				let weightSum = 0;
				for (let i = 0; i < this.haveShotList.length; i++) {
					weightSum += this.haveShotList[i].weight;
					if (random <= weightSum) {
						this.selectedItem = this.haveShotList[i];
						this.selectedIndex = i;
						console.log(this.selectedItem, "试一试出来的");
						this.$showToast(
							`${this.selectedItem.name}-权重：${this.selectedItem.weight}-概率：${this.calculateProbability(this.selectedItem.weight)}`
							)
						break;
					}
				}
			},
			// 概率计算
			calculateProbability(weight) {
				return ((weight / this.totalWeight) * 100).toFixed(2);
			},
			// 通过ID获取机台详情
			machinesDetailFn() {
				this.$http('/v1/machines/detail/' + this.machineId).then(res => {
					console.log(res, "获取机台详情");
					if (res.code == 0) {
						const data = res.data;
						this.machine = data.machine;
						// 试一试列表
						this.haveShotList = data.all_images.filter(item => {
							return item.parent_id == 0;
						})
						this.totalWeight = this.haveShotList.reduce((sum, item) => sum + item.weight, 0);
						console.log(this.totalWeight, '总权重', this.haveShotList);
						/* 数组item权重和=总权重
						a权重 1
						b权重 2
						总权重 1 +2 =3
						a 1/3
						b 2/3 */
						// this.shopsDetail = res.data.shop;
						// this.is_followed = res.data.is_followed;
					} else {
						this.$showToast(res.msg)
					}
				})

			},
			// 试一试, 就是纯播放前端效果, 不花钱, 当后台传递的参数里,可以`试一试`的时候, 显示这个按钮, 每一个奖品的概率 = 自身的权重/权重总和
			sys() {
				console.log('试一试');
				this.$showToast('试一试')
			},
			// 扭蛋-抽奖
			gashaponFn(count = 1) {
				this.$http('/v1/machines/gashapon', {
					"machine_id": Number(this.machineId),
					"count": Number(count)
				}, 'POST').then(res => {
					console.log(res);
					if (res.code == 0) {}
					if (res.code == 1003) {
						// msg: "抽奖机会不足，请购买后再尝试参与机台抽奖~"
						this.ordersCreateFn(count, 'lottery')
					}
					this.$showToast(res.msg)
				})
			},
			ordersCreateFn(num, type) {
				this.$http('/v1/orders/create', {
					"type": type,
					"shop_id": Number(this.shopId),
					"machine_id": Number(this.machineId),
					"num": num
				}, 'POST').then(res => {
					console.log(res);
					if (res.code == 0) {
						// uni.navigateTo({
						// 	url:'/pages/my/orderConfirmation?'
						// })
						let wechatParams = res.data.wechat_params
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: wechatParams.timeStamp,
							nonceStr: wechatParams.nonceStr,
							package: wechatParams.package,
							signType: wechatParams.signType,
							paySign: wechatParams.paySign,
							success: function(res) {
								console.log('success:' + JSON.stringify(res));
							},
							fail: function(err) {
								console.log('fail:' + JSON.stringify(err));
							}
						});

					} else {}
					this.$showToast(res.msg)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		@include flexLayout(center, center);
		flex-direction: column;
		min-height: 100vh;

		.item {
			@include flexLayout(center, center);
		}
	}
</style>